//
//  XS_KeChengVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/30.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import SnapKit

class XS_KeChengVC: XS_KCBaseVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let model = model else { return }
        dataPS.onNext(model)
    }
    override func upScroll(_ top: UIView) {
        guard let model = model else { return }
        var last = top
        if model.curriculum.teacherBOList.count > 0 {
            let teacher = XS_KCTeachers()
            ss.addSubview(teacher)
            teacher.snp.makeConstraints({
                $0.left.width.equalToSuperview()
                $0.top.equalTo(last.snp.bottom)
                $0.bottom.lessThanOrEqualToSuperview()
            })
            teacher.modelPS.onNext(model.curriculum.teacherBOList)
            last = teacher
        }
        
        if let item = model.curriculum.curriculumCertificateDto, item.id > 0 {
            let zhengshu = XS_KCZhengshu()
            ss.addSubview(zhengshu)
            zhengshu.snp.makeConstraints({
                $0.left.width.equalToSuperview()
                $0.top.equalTo(last.snp.bottom)
                $0.bottom.lessThanOrEqualToSuperview()
            })
//            zhengshu.modelPS.onNext(("可获证书", item.imgUrl))
            zhengshu.zhengshuNameModelPS.onNext(("可获证书", item.name))
            let tap = UITapGestureRecognizer()
            zhengshu.addGestureRecognizer(tap)
            tap.rx.event.asDriver()
                .drive(onNext: { _ in
                    let vc = XS_ZhengshuDetailVC()
                    vc.id = item.id
                    XS_NVC.shared.pushViewController(vc, animated: true)
                }).disposed(by: disposeBag)
            last = zhengshu
        }
        
        if model.curriculum.isCurriculumSeries == "yes" { // 是否系列课（是：yes，否：no）
            let view = UIView()
            view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            ss.addSubview(view)
            view.snp.makeConstraints({
                $0.left.width.equalToSuperview()
                $0.top.equalTo(last.snp.bottom).offset(.scale*8)
                $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*8)
            })
            
            XS_NetWork.requestJson("/hour/queryLearnWay", parameters: ["id":id])
                .mapModels(type: XS_KCqueryLearnWayM.self)
                .subscribe(onNext: { models, resp in
                    guard models.count > 0 else { return }
                    let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "学习路线")
                    view.addSubview(label)
                    label.snp.makeConstraints({
                        $0.left.top.equalTo(.scale*16)
                    })
                    let line = UIView()
                    line.backgroundColor = #colorLiteral(red: 0.9411764706, green: 0.9490196078, blue: 0.968627451, alpha: 1)
                    view.addSubview(line)
                    
                    var last = view
                    var fistItem: UIView!
                    var lastItem: UIView!
                    for (index, item) in models.enumerated() {
                        let imgV = UIImageView(image: UIImage(named: "编组 3_1"))
                        view.addSubview(imgV)
                        imgV.snp.makeConstraints({
                            $0.width.height.equalTo(.scale*24)
                            $0.left.equalTo(.scale*16)
                            if index == 0 {
                                $0.top.equalTo(.scale*64)
                            } else {
                                $0.top.equalTo(last.snp.bottom).offset(.scale*24)
                            }
                        })
//                        let numLab = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: String(format: "%.2d", index+1))
//                        view.addSubview(numLab)
//                        numLab.snp.makeConstraints({
//                            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
//                            $0.centerY.equalTo(imgV.snp.centerY)
//                        })
                        let titleLab = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: item.chapterName)
                        view.addSubview(titleLab)
                        titleLab.snp.makeConstraints({
                            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
                            $0.centerY.equalTo(imgV.snp.centerY)
                        })
                        let dLab = UILabel.xsLabel(size: .scale*13, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), lines: 0, text: item.description)
                        view.addSubview(dLab)
                        dLab.snp.makeConstraints({
                            $0.left.equalTo(.scale*52)
                            $0.width.lessThanOrEqualTo(.scale*307)
                            $0.top.equalTo(imgV.snp.bottom).offset(.scale*7)
                            $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*16)
                        })
                        last = dLab
                        
                        for item in item.curriculumHourDtoList {
                            let bg = UIView()
                            let tap = UITapGestureRecognizer()
                            bg.addGestureRecognizer(tap)
                            tap.rx.event.asDriver()
                                .drive(onNext: { [weak self] _ in
                                    guard let `self` = self else { return }
                                    XS_NetWork.requestJson("/file/playVideo", parameters: ["id":item.id])
                                        .mapModel(type: XS_KCplayVideoM.self)
                                        .subscribe(onNext: { [weak self] video, resp in
                                            guard let `self` = self else { return }
                                            if resp.code == "00403" { // 购买
                                                guard XS_Singleton.shared.infoModel != nil else {
                                                    XS_NVC.shared.toLogin(false)
                                                    return
                                                }
                                                let buyVC = XS_BuyVC()
                                                buyVC.courseId = "\(model.curriculum.id)"
                                                buyVC.courseClassification = "online"
                                                XS_NVC.shared.pushViewController(buyVC, animated: true)
                                                return
                                            }
                                            guard resp.success, let video = video else { return }
                                            let vc = XS_KCDetailVC()
                                            vc.curriculum = model.curriculum
                                            vc.model = video
                                            vc.id = item.id
                                            self.navigationController?.pushViewController(vc, animated: true)
                                        }).disposed(by: self.disposeBag)
                                }).disposed(by: self.disposeBag)
                            
                            bg.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
                            view.addSubview(bg)
                            bg.snp.makeConstraints({
                                $0.width.equalTo(.scale*307)
                                $0.height.equalTo(.scale*88)
                                $0.left.equalTo(.scale*52)
                                $0.top.equalTo(last.snp.bottom).offset(.scale*8)
                                $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*16)
                            })
                            
                            let imgV = UIImageView()
                            imgV.sd_setImage(with: URL(string: item.imgUrl))
                            let nameLab = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: item.curriculumHourName)
                            let dLab = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: item.description)
                            let pLab = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.watchNum)人在学习")
                            if item.isWatch == "yes" {
                                let isWatchLab = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1), text: "可试看")
                                isWatchLab.backgroundColor = #colorLiteral(red: 0.831372549, green: 0.9490196078, blue: 0.9215686275, alpha: 1)
                                isWatchLab.textAlignment = .center
                                bg.addSubview(isWatchLab)
                                isWatchLab.snp.makeConstraints {
                                    $0.bottom.equalTo(0)
                                    $0.right.equalTo(-.scale*10)
                                    $0.width.equalTo(.scale*41)
                                    $0.height.equalTo(.scale*18)
                                }
                            }
                            bg.addSubview(imgV)
                            bg.addSubview(nameLab)
                            bg.addSubview(dLab)
                            bg.addSubview(pLab)
                            imgV.snp.makeConstraints({
                                $0.width.equalTo(.scale*88)
                                $0.height.equalTo(.scale*64)
                                $0.centerY.equalToSuperview()
                                $0.left.equalTo(.scale*12)
                            })
                            nameLab.snp.makeConstraints({
                                $0.top.equalTo(.scale*12)
                                $0.left.equalTo(imgV.snp.right).offset(.scale*8)
                                $0.right.lessThanOrEqualTo(-.scale*12)
                            })
                            dLab.snp.makeConstraints({
                                $0.top.equalTo(nameLab.snp.bottom).offset(.scale*4)
                                $0.left.equalTo(imgV.snp.right).offset(.scale*8)
                                $0.right.lessThanOrEqualTo(-.scale*12)
                            })
                            pLab.snp.makeConstraints({
                                $0.bottom.equalTo(-.scale*12)
                                $0.left.equalTo(imgV.snp.right).offset(.scale*8)
                                $0.right.lessThanOrEqualTo(-.scale*12)
                            })
                            
                            last = bg
                        }
                        
                        if index == 0 {
                            fistItem = imgV
                        }
                        if index == models.count - 1 {
                            lastItem = imgV
                        }
                    }
                    line.snp.makeConstraints({
                        $0.width.equalTo(.scale*2)
                        $0.centerX.equalTo(fistItem.snp.centerX)
                        $0.top.equalTo(fistItem.snp.centerY)
                        $0.bottom.equalTo(lastItem.snp.centerY)
                    })
                }).disposed(by: disposeBag)
            
            last = view
            
            let change = getChange(model: model)
            ss.addSubview(change)
            change.snp.makeConstraints({
                $0.top.equalTo(last.snp.bottom).offset(.scale*8)
                $0.height.equalTo(.scale*160)
                $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*8)
                $0.left.width.equalToSuperview()
            })
        } else {
            
            let biaoqian = XS_KCBiaoqian(["介绍", "目录", "快学"]) { [weak self] index in
                guard let `self` = self else { return nil }
                switch index {
                case 0: return self.getJieshao(model)
                case 1:
                    let mulu = XS_KCMulu(model.curriculum.id)
                    mulu.isBuy = model.curriculum.isBuy == "yes"
                    self.dataPS.subscribe(onNext: { model in
                        mulu.isBuy = model.curriculum.isBuy == "yes"
                    }).disposed(by: self.disposeBag)
                    mulu.actionPS.subscribe(onNext: { [weak self] item in
                        guard let `self` = self else { return }
                        XS_NetWork.requestJson("/file/playVideo", parameters: ["id":item.id])
                            .mapModel(type: XS_KCplayVideoM.self)
                            .subscribe(onNext: { [weak self] video, resp in
                                guard let `self` = self else { return }
                                if resp.code == "00403" { // 购买
                                    guard XS_Singleton.shared.infoModel != nil else {
                                        XS_NVC.shared.toLogin(false)
                                        return
                                    }
                                    let buyVC = XS_BuyVC()
                                    buyVC.courseId = "\(model.curriculum.id)"
                                    buyVC.courseClassification = "online"
                                    XS_NVC.shared.pushViewController(buyVC, animated: true)
                                    return
                                }
                                guard resp.success, let video = video else { return }
                                let vc = XS_KCDetailVC()
                                vc.curriculum = model.curriculum
                                vc.model = video
                                vc.id = item.id
                                self.navigationController?.pushViewController(vc, animated: true)
                            }).disposed(by: self.disposeBag)
                    }).disposed(by: self.disposeBag)
                    return mulu
                case 2: return self.getFaxian(model)
                default: return nil
                }
            }
            ss.addSubview(biaoqian)
            biaoqian.snp.makeConstraints({
                $0.top.equalTo(last.snp.bottom).offset(.scale*8)
                $0.left.width.equalToSuperview()
                $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*8)
            })
            last = biaoqian
        }
        
        dataPS.subscribe(onNext: { [weak self] model in
            guard let `self` = self else { return }
            if model.curriculum.isBuy == "yes" { // 当前用户是否购买该课程(购买yes 未购买no 游客no)
                if model.curriculum.curriculumForm == "offline" {
                    self.btnTypePS.onNext(("已报名", #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)))
                } else {
                    self.btnTypePS.onNext(("立即学习", #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)))
                }
            } else if model.curriculum.isFree == "userFree" { // 是否免费（是：userFree，否：userPay）
                self.btnTypePS.onNext(("立即领取", #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)))
            } else {
                self.btnTypePS.onNext(("立即购买", #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)))
            }
        }).disposed(by: disposeBag)
        
        
//    model.curriculum.curriculumForm == "offline" { // 课程形式（线下：offline,线上：online)
//        var vipIsFree = "" // 会员是否免费（是：vipFree, 否：vipPay）
    }
    
    func getFaxian(_ model: XS_KeChengM) -> UIView {
        let view = UIView()
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: .scale*166, height: .scale*281)
        flowLayout.minimumLineSpacing = .scale*16
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: .scale*16, left: .scale*16, bottom: .scale*16, right: .scale*16)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.bounces = false
        collection.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        view.addSubview(collection)
        var constraint: Constraint!
        collection.snp.makeConstraints {
            $0.left.top.right.equalToSuperview()
            constraint = $0.height.equalTo(.scale*32).constraint
            $0.bottom.lessThanOrEqualTo(-.scale*8)
        }
        collection.rx.observe(CGSize.self, "contentSize")
            .subscribe(onNext: { size in
                guard let size = size, size != .zero else { return }
                constraint.update(offset: size.height)
            }).disposed(by: self.disposeBag)
        collection.register(XS_FaxianCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, XS_discoverQuickLearnM>>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_FaxianCell
            cell.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
            cell.layer.masksToBounds = false
            cell.modelPS.onNext(it)
            return cell
        })
        
        let param: [String:Any] = [
            "pageNum":1,
            "pageSize":"100",
            "industryId":model.curriculum.industryId
        ]
        
        XS_NetWork.requestJson("/quick/discoverQuickLearn", parameters: param)
            .mapModel(type: XS_ListM<XS_discoverQuickLearnM>.self)
            .compactMap { $0.0?.records }
            .asDriver(onErrorJustReturn: [])
            .flatMapLatest { Driver.just([SectionModel<String, XS_discoverQuickLearnM>(model: "", items: $0)]) }
            .drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        collection.rx.modelSelected(XS_discoverQuickLearnM.self)
            .asDriver()
            .drive(onNext: { item in
                let vc = XS_KuaiXueDetailVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        return view
    }
    func getJieshao(_ model: XS_KeChengM) -> UIView {
        let view = UIView()
        
        let bg = UIView()
        bg.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view.addSubview(bg)
        bg.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
        })
        let imgV = UIImageView()
        bg.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.equalTo(.scale*16)
            $0.right.bottom.equalTo(-.scale*16)
            $0.height.equalTo(1)
        })
        imgV.sd_setImage(with: URL(string: model.curriculum.descriptionImgUrl)) { img, _, _, _ in
            imgV.snp.remakeConstraints({
                $0.left.top.equalTo(.scale*16)
                $0.right.bottom.equalTo(-.scale*16)
                if let size = img?.size, size.width > 0 {
                    $0.height.equalTo(imgV.snp.width).multipliedBy(size.height/size.width)
                }
            })
        }
        
        let change = getChange(model: model)
        view.addSubview(change)
        change.snp.makeConstraints({
            $0.top.equalTo(bg.snp.bottom).offset(.scale*8)
            $0.height.equalTo(.scale*160)
            $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*8)
            $0.left.width.equalToSuperview()
        })
        
        return view
    }

    func getChange(model: XS_KeChengM) -> UIView {
        let collections = XD_RecommendCollView()
        collections.curriculumId = model.curriculum.id
        collections.reLoadData()
        return collections
    }
}
